/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
// 先实现promise的构造函数,promise的三大状态为pending,fulfilled,rejected
// 先简单实现promise的初始状态，在观察
const PENDING = 'pending'  // 等待
const FULFILLED = 'fulfilled'  // 成功
const REJECTED = 'rejected'  // 失败

class MyPromise {
    constructor(callback) {
        callback(this.resolve, this.reject)
    }
    // 异步回调成功的事件数组
    successlist = []
    // 异步回调失败事件的数组
    faillist = []
    // 成功回调的参数保存
    successinfo = null
    // 失败回调内容的保存
    failinfo = null
    // prommise状态
    status = PENDING
    resolve = (value) => {
        // 状态更改成功
        if (this.status !== PENDING) return
        this.status = FULFILLED
        // 保存成功信息
        this.successinfo = value
        // 异步成功回调执行
        // 传递成功的数据
        while (this.successlist.length) this.successlist.shift()(value)
    }
    reject = (reason) => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        // 保存失败原因
        this.failinfo = reason
        // 异步失败回调执行
        // 给函数传递失败原因
        while (this.faillist.length) this.successlist.shift()(reason)
    }
    then(res, rej) {
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    let x = res(this.successinfo)
                    // 判断 x 的值是普通还是promise对象
                    // 如果是普通直接调用resolve
                    // 如果是promise对象 查看promise返回结果
                    // 再根据promise对象的返回结果决定调用resovle还是reject
                    resPromise(promise2, x, resolve, reject)
                }, 0)
            } else if (this.status === REJECTED) {
                let y = rej(this.failinfo)
                resPromise(promise2, y, resolve, reject)
            } else {
                this.successlist.push(res)
                this.faillist.push(rej)
            }
        })
        return promise2
    }
}
function resPromise(promise, x, resolve, reject) {
    if (promise === x) {
        return reject(new TypeError('不能自己调用自己'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}
let promise = new MyPromise((resolve, reject) => {
    // setTimeout(() => {
    resolve('成功')
    // }, 1000)
})

promise.then(value => {
    console.log(value);
    return 100
}, reason => {
    console.log(reason);
}).then(value => {
    console.log(value);
}, reason => {
    console.log(reason);
})
